package com.yiwan.app.preventionsis.ui;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.app.tianwan.tianwanframe.ui.FrameActivity;
import com.app.tianwan.tianwanframe.utils.LogUtil;
import com.umeng.analytics.MobclickAgent;
import com.yiwan.app.preventionsis.R;
import com.yiwan.app.preventionsis.bean.ImageRes;
import com.yiwan.app.preventionsis.config.GlobalCfg;
import com.yiwan.app.preventionsis.config.ImageResManager;
import com.yiwan.app.preventionsis.fragment.FragmentMenu;
import com.yiwan.app.preventionsis.fragment.FragmentShow;
import com.yiwan.app.preventionsis.util.AppConfig;

public class ShowActivity extends FrameActivity {

    private RelativeLayout controlLayer;

    private ViewPager viewPager;
    private PictureSlidePagerAdapter pagerAdapter;

//	private ImageButton[] btnMenu = null;
//	private static final int NOF_MENU = 7;
//	private HorizontalScrollView showScroll;

    //private ImageButton btnPull = null;

    private Button btnPrev = null;
    private Button btnNext = null;
    private Button btnBack = null;

    //	private boolean isMenuShown = false;
    private boolean isMenuClickable = false;

//	private int menuMarginTop;

    private Animation animAlphaIn;
    private Animation animAlphaOut;
    private boolean asInRunning;
    private AnimationSet animSetAsIn;
    private AnimationSet animSetAsOut;
    private boolean asOutRunning;
    private AnimationSet animSetAsInLight;
    private AnimationSet animSetAsOutLight;
    private Animation animAlphaInLight;
    private Animation animAlphaOutLight;

//	private Animation menuShow;
//	private Animation menuHide;
//	
//	private Animation rotateCWise90;
//	private Animation rotateCCWise90;
//	private AnimationSet rtCWise90;
//	private AnimationSet rtCCWise90;

    private Animation animAlphaoutSlow;
    private AnimationSet animSetAlphaOutSlow;

    private long wrapTime = 0;

    @Override
    public int getRootView() {
        return R.layout.activity_show;
    }

    @Override
    public void initView() {
        controlLayer = (RelativeLayout) findViewById(R.id.control_layer);
//		btnMenu = new ImageButton[NOF_MENU];
//		showScroll = (HorizontalScrollView) findViewById(R.id.show_menu);
//		btnMenu[0] = (ImageButton) findViewById(R.id.menu0);
//		btnMenu[1] = (ImageButton) findViewById(R.id.menu1);
//		btnMenu[2] = (ImageButton) findViewById(R.id.menu2);
//		btnMenu[3] = (ImageButton) findViewById(R.id.menu3);
//		btnMenu[4] = (ImageButton) findViewById(R.id.menu4);
//		btnMenu[5] = (ImageButton) findViewById(R.id.menu5);
//		btnMenu[6] = (ImageButton) findViewById(R.id.menu6);
        //btnPull = (ImageButton) findViewById(R.id.show_menu_pull);
        btnPrev = (Button) findViewById(R.id.show_backward);
        btnNext = (Button) findViewById(R.id.show_forward);
        btnBack = (Button) findViewById(R.id.show_back);

//		for(ImageButton button : btnMenu){
//			button.setOnClickListener(new MyOnClickListener());
//		}
        //btnPull.setOnClickListener(new MyOnClickListener());
        btnPrev.setOnClickListener(new MyOnClickListener());
        btnNext.setOnClickListener(new MyOnClickListener());
        btnBack.setOnClickListener(new MyOnClickListener());

//		btnPull.setAlpha(0.5f);
        controlLayer.setAlpha(1f);
        btnPrev.setAlpha(0.3f);
        btnNext.setAlpha(0.3f);
        btnBack.setAlpha(0.5f);

        //menuMarginTop = menuContainer.getLayoutParams().height;

        viewPager = (ViewPager) findViewById(R.id.show_viewpager);

        animAlphaoutSlow = AnimationUtils.loadAnimation(ShowActivity.this, R.anim.alphaoutslow);
        animSetAlphaOutSlow = new AnimationSet(true);
        animSetAlphaOutSlow.addAnimation(animAlphaoutSlow);
        animSetAlphaOutSlow.setFillAfter(true);
        animSetAlphaOutSlow.setAnimationListener(new AlphaInListener());

        animAlphaIn = AnimationUtils.loadAnimation(ShowActivity.this, R.anim.alphain);
        animAlphaOut = AnimationUtils.loadAnimation(ShowActivity.this, R.anim.alphaout);
        animSetAsIn = new AnimationSet(true);
        animSetAsIn.addAnimation(animAlphaIn);
        animSetAsIn.setFillAfter(true);
        animSetAsOut = new AnimationSet(true);
        animSetAsOut.addAnimation(animAlphaOut);
        animSetAsOut.setFillAfter(true);
        animAlphaIn.setAnimationListener(new AlphaInListener());
        animAlphaOut.setAnimationListener(new AlphaOutListenr());

        animAlphaInLight = AnimationUtils.loadAnimation(ShowActivity.this, R.anim.alphainlight);
        animSetAsInLight = new AnimationSet(true);
        animAlphaOutLight = AnimationUtils.loadAnimation(ShowActivity.this, R.anim.alphaoutlight);
        animSetAsOutLight = new AnimationSet(true);

        isMenuClickable = true;
        btnPrev.setVisibility(View.INVISIBLE);

        viewPager.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //Log.d("Viewpager", "Viewpager.onTouch");
                btnPrev.setAlpha(0.3f);
                btnNext.setAlpha(0.3f);
                showMenu();
                return false;
            }
        });

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                if (arg0 == 0) {
                    btnPrev.setVisibility(View.INVISIBLE);
                    btnNext.setVisibility(View.VISIBLE);
                } else if (arg0 == pagerAdapter.getCount() - 1) {
                    btnPrev.setVisibility(View.VISIBLE);
                    btnNext.setVisibility(View.INVISIBLE);
                } else {
                    btnPrev.setVisibility(View.VISIBLE);
                    btnNext.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        int showType = intent.getIntExtra(AppConfig.INTNET_SHOW_TYPE, 0);
        pagerAdapter = new PictureSlidePagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);
        viewPager.setCurrentItem(pagerAdapter.getInitItemId(showType));
    }

    private class AlphaInListener implements AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {
            //Log.d("alphaIn", "onAnimationStart");
            controlLayer.setAlpha(1f);
            asInRunning = true;
            asOutRunning = false;
            isMenuClickable = true;
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            //Log.d("alphaIn", "onAnimationEnd");
            asInRunning = false;
            asOutRunning = false;
            controlLayer.clearAnimation();
            controlLayer.startAnimation(animSetAsOut);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

    }

    private class AlphaOutListenr implements AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {
            //Log.d("alphaOut", "onAnimationStart");
            asInRunning = false;
            asOutRunning = true;
            isMenuClickable = true;
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            //Log.d("alphaOut", "onAnimationEnd");
            controlLayer.clearAnimation();
            controlLayer.setAlpha(0);
            asInRunning = false;
            asOutRunning = false;
            isMenuClickable = false;
            btnPrev.setAlpha(0.6f);
            btnNext.setAlpha(0.6f);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus) {
            controlLayer.startAnimation(animSetAsOut);
        }
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onStart() {
        asInRunning = false;
        asOutRunning = false;
        super.onStart();
    }

    @Override
    protected void onStop() {
        animSetAsIn.cancel();
        animSetAsIn.reset();
        animSetAsOut.cancel();
        animSetAsOut.reset();
        super.onStop();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onBackPressed() {
        //if (viewPager.getCurrentItem() == 0) {
        // If the user is currently looking at the first step, allow the system to handle the
        // Back button. This calls finish() on this activity and pops the back stack.
        super.onBackPressed();
        //} else {
        // Otherwise, select the previous step.
        //viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
        //}
    }

    private class MyOnClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            if (!isMenuClickable) {
                showMenu();
                return;
            }
            if (v == btnBack) {
                finish();
            } else if (v == btnPrev) {
                btnNext.setAlpha(0.4f);
                btnPrev.setAlpha(0.8f);
                int i = viewPager.getCurrentItem();
                if (i > 0) {
                    viewPager.setCurrentItem(viewPager.getCurrentItem() - 1, true);
                } else {
                    Toast.makeText(ShowActivity.this, "已经是第一张了", Toast.LENGTH_SHORT).show();
                }
            } else if (v == btnNext) {
                btnNext.setAlpha(0.8f);
                btnPrev.setAlpha(0.4f);
                int i = viewPager.getCurrentItem();
                if (i < viewPager.getAdapter().getCount() - 1) {
                    viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
                }
            }

            showMenu();
        }
    }

    /**
     * ��ʾ���ƽ���
     */
    private void showMenu() {
        if (asInRunning) {
            //Log.d("showMenu", "asIn Running");
        } else if (asOutRunning) {
            //Log.d("showMenu", "asOut Running");
            controlLayer.clearAnimation();
            animSetAsOut.reset();
            //controlLayer.setAlpha(1);
            controlLayer.startAnimation(animSetAsOut);
            isMenuClickable = true;
        } else {
            //Log.d("showMenu", "No Running");
            controlLayer.startAnimation(animSetAsIn);
        }
    }

    public void pageToIndex(int showType) {
        int showInd = pagerAdapter.getInitItemId(showType);
        viewPager.setCurrentItem(showInd, true);
    }

    private class PictureSlidePagerAdapter extends FragmentStatePagerAdapter {

        private static final int SHOW_TYPE_IMG = 0;
        private static final int SHOW_TYPE = 7;

        private int pageNum = 0;
        private int[] showimgOffset;

        public PictureSlidePagerAdapter(FragmentManager fm) {
            super(fm);
            ImageResManager imageResManager = ImageResManager.getInstance();
            showimgOffset = new int[SHOW_TYPE];
            showimgOffset[0] = 0;
            showimgOffset[1] = imageResManager.getImgIntro().size();
            showimgOffset[2] = showimgOffset[1] + imageResManager.getImgCheet().size();
            showimgOffset[3] = showimgOffset[2] + imageResManager.getImgFire().size();
            showimgOffset[4] = showimgOffset[3] + imageResManager.getImgRob().size();
            showimgOffset[5] = showimgOffset[4] + imageResManager.getImgSteal().size();
            showimgOffset[6] = showimgOffset[5] + imageResManager.getImgSelfSave().size();
            pageNum = showimgOffset[6] + imageResManager.getImgterror().size();
        }

        public int getInitItemId(int showType) {
            return showimgOffset[showType];
        }

        @Override
        public Fragment getItem(int index) {
            if (index < pageNum) {
                ImageRes ir;
                int imgType = 0;
                ImageResManager irm = ImageResManager.getInstance();
                if(index < showimgOffset[1]){
                    ir = irm.getImgIntro().get(index);
                    imgType = GlobalCfg.IMG_TYPE_INTRO;
                } else if(index < showimgOffset[2]){
                    ir = irm.getImgCheet().get(index - showimgOffset[1]);
                    imgType = GlobalCfg.IMG_TYPE_CHEAT;
                } else if(index < showimgOffset[3]){
                    ir = irm.getImgFire().get(index - showimgOffset[2]);
                    imgType = GlobalCfg.IMG_TYPE_FIRE;
                } else if(index < showimgOffset[4]){
                    ir = irm.getImgRob().get(index - showimgOffset[3]);
                    imgType = GlobalCfg.IMG_TYPE_ROB;
                } else if(index < showimgOffset[5]){
                    ir = irm.getImgSteal().get(index - showimgOffset[4]);
                    imgType = GlobalCfg.IMG_TYPE_STEAL;
                } else if(index < showimgOffset[6]){
                    ir = irm.getImgSelfSave().get(index - showimgOffset[5]);
                    imgType = GlobalCfg.IMG_TYPE_SAVE_SELF;
                } else {
                    ir = irm.getImgterror().get(index - showimgOffset[6]);
                    imgType = GlobalCfg.IMG_TYPE_TERROR;
                }
                LogUtil.d("getImageRes: " + ir.toString());
                return FragmentShow.newInstance(ShowActivity.this, ir, imgType);
            } else if (index == pageNum) {
                return FragmentMenu.newInstance(ShowActivity.this);
            } else return null;
        }

        @Override
        public void destroyItem(android.view.ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
        }


        @Override
        public int getCount() {
            return pageNum + 1;
        }
    }

    public void changeBtnLRAlpha(float f) {
        btnNext.setAlpha(f);
        btnPrev.setAlpha(f);
    }

    class ControlLayer extends RelativeLayout {

        public ControlLayer(Context context) {
            super(context);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            showMenu();
            return super.onTouchEvent(event);
        }
    }
}
